package com.ycsj.goldmedalnewconcept.adapter;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import android.R.integer;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.speech.SpeechRecognizer;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.PopupWindow.OnDismissListener;
import cn.smssdk.SMSSDK.InitFlag;

import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.AnswerInfo;
import com.ycsj.goldmedalnewconcept.iflytek.ise.Result;
import com.ycsj.goldmedalnewconcept.iflytek.ise.XmlResultParser;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;

@SuppressWarnings("unused")
public class ClassListAdapter extends CommonAdapter<AnswerInfo> {

	private Context context;
	private Activity activity;
	private MediaPlayer player;
	private List<AnswerInfo> datas;

	// 录音的弹框PopUpWinow相关
	private View view;
	private ImageView lvPopRecord;
	private PopupWindow popupWindow;
	// 帧动画对象
	private AnimationDrawable animationDrawable;
	private AnimationDrawable newAnimationDrawable;

	// 讯飞SDK对象
	private SpeechEvaluator mSpeechEvaluator;

	// 控制松手是否显示加载框的标记
	private boolean flag = true;

	public ClassListAdapter(Context context, Activity activity,
			List<AnswerInfo> datas, int layoutId) {
		super(context, datas, layoutId);
		this.context = context;
		setParams(context);
		this.datas = datas;
		this.activity = activity;
	}

	@Override
	public void convert(final ViewHolder holder, final AnswerInfo info) {
		// 获取题目
		TextView tvContent = holder.getView(R.id.tv_topic);

		tvContent.setText(info.questionContent);

		// 顶部的线性布局
		LinearLayout llTopPlay = holder.getView(R.id.ll_top_play);

		// 顶部的喇叭和播放图片
		final ImageView lvTopLaBa = holder.getView(R.id.lv_top_laba);

		
		// 播放录音按钮
		final ImageView lvPlay = holder.getView(R.id.lv_replay);

		// 录音按钮
		final ImageView lvRecord = holder.getView(R.id.lv_record);

		// 加载框
		LinearLayout llLoading = holder.getView(R.id.ll_loading);

		// 记录分数的TextView
		TextView tvScore = holder.getView(R.id.tv_score);

		// info.score

		// DecimalFormat df = new DecimalFormat("#.0");

		// float a = 123.2334f;
		float b = (float) (Math.round(info.score * 10)) / 10;
		tvScore.setText(b + " 分");

		// 根据状态配置显示状态
		if (info.isPlay) {
			// 是否播放状态
			lvPlay.setImageResource(R.drawable.stopcloze);
		} else {
			lvPlay.setImageResource(R.drawable.playcloze);
		}
		
		// 根据状态配置显示播放课文状态
		if (info.isPlayUrl) {
			// 是否播放状态
//			lvTopLaBa.setImageResource(R.drawable.stopcloze);
		} else {
			lvTopLaBa.setImageResource(R.drawable.lb);
		}

		// 控制显示分数的状态
		if (info.isShowScore) {
			// 是否显示分数
			tvScore.setVisibility(View.VISIBLE);
		} else {
			tvScore.setVisibility(View.INVISIBLE);
		}

		// 控制是否显示加载框的状态
		if (info.isShowDialog) {
			// 是否需要显示加载框的状态值
			llLoading.setVisibility(View.VISIBLE);
		} else {
			llLoading.setVisibility(View.INVISIBLE);
		}
		
		
		// 顶部播放课文按钮的事件
		llTopPlay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				// 清除动画效果
				if (null != newAnimationDrawable) {
					newAnimationDrawable.stop();
					lvTopLaBa.setImageResource(R.drawable.lb);
				}
				
				
				// 获取录音文件的地址
				if (!TextUtils.isEmpty(info.path)) {
					
					
					// 给顶部的图片设置帧动画
					lvTopLaBa.setImageResource(R.drawable.lv_frame_b);

					// 获取帧动画对象
					newAnimationDrawable = (AnimationDrawable) lvTopLaBa.getDrawable();

					
					// 同步状态
					// 让其它条目的播放按钮变成停止状态
					for (int i = 0; i < datas.size(); i++) {
							datas.get(i).isPlay = false;
					}

					for (int i = 0; i < datas.size(); i++) {
						if (info != datas.get(i)) {
							datas.get(i).isPlayUrl = false;
						}
					}
					
					info.isPlayUrl = true;
//					info.isPlay = true;

					notifyDataSetChanged();

					// 创建音频播放对象
					if (player != null) {
						player.release();
					}
					player = new MediaPlayer();

					// 设置完成播放的监听
					player.setOnCompletionListener(new OnCompletionListener() {

						@Override
						public void onCompletion(MediaPlayer mp) {
							if (player != null) {
								player.release();
								player = null;
							}

							// 改变图标
							info.isPlay = false;

							
							notifyDataSetChanged();
							
							// 清除动画效果
							if (null != newAnimationDrawable) {
								newAnimationDrawable.stop();
								lvTopLaBa.setImageResource(R.drawable.lb);
							}
						}
					});

					// 播放课文音频
					try {
						player.setDataSource(info.path);
						player.prepareAsync();

						player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
							@Override
							public void onPrepared(MediaPlayer mp) {

								player.start();
								// 执行帧动画
								if (null != newAnimationDrawable) {
									newAnimationDrawable.start();
								}
							}
						});

					} catch (Exception e) {
						Log.i("test", e.toString());
					}
				}
			}
		});

		// 录音按钮的录音事件
		lvRecord.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:

					// 按下的时候重置加载框的状态
					flag = true;

					// 弹框操作
					showRecordPop();

					// 释放播放器对象
					if (null != player) {
						player.release();
					}

					// 录音的操作
					// 获取Vibrate震动对象
					Vibrator vibrator = (Vibrator) context
							.getSystemService(Service.VIBRATOR_SERVICE);
					vibrator.vibrate(500);

					if (null != mSpeechEvaluator) {

						// 重新配置存储位置
						setAudioPath(info.postion);

						// 评测功能
						mSpeechEvaluator.startEvaluating(info.questionContent,
								null, new EvaluatorListener() {

									// volume音量值0~30，data音频数据
									@Override
									public void onVolumeChanged(int volume,
											byte[] data) {

									}

									// 结果回调，评测过程中可能会多次调用该方法，isLast为true则为最后结果
									@Override
									public void onResult(
											EvaluatorResult result,
											boolean isLast) {
										if (isLast) {
											StringBuilder builder = new StringBuilder();
											builder.append(result
													.getResultString());

											XmlResultParser resultParser = new XmlResultParser();
											Result result1 = resultParser
													.parse(result
															.getResultString());

											if (!TextUtils.isEmpty(builder)) {
												float a = result1.total_score;
												float b = (float) (Math
														.round(a * 10)) / 10;
												flag = false;
												// 重新设置分数
												info.score = b;
												// 显示分数的TextView
												info.isShowScore = true;
												// 隐藏加载框
												info.isShowDialog = false;
												// 重新配置录音地址
												info.audioPath = getAmrPath(info.postion);

												// 重置状态
												for (int i = 0; i < datas
														.size(); i++) {
													datas.get(i).isPlay = false;
												}

												// 通知适配器刷新
												notifyDataSetChanged();

												// 播放科大讯飞的评分播放对应语音
												AssetManager assetManager = context
														.getAssets();

												if (player != null) {
													player.release();
												}

												player = new MediaPlayer();

												try {
													AssetFileDescriptor fileDescriptor1 = assetManager
															.openFd("1.mp3");
													AssetFileDescriptor fileDescriptor2 = assetManager
															.openFd("2.mp3");
													AssetFileDescriptor fileDescriptor3 = assetManager
															.openFd("3.mp3");
													AssetFileDescriptor fileDescriptor4 = assetManager
															.openFd("4.mp3");
													AssetFileDescriptor fileDescriptor5 = assetManager
															.openFd("5.mp3");
													if (b < 1.0) {
														player.setDataSource(
																fileDescriptor1
																		.getFileDescriptor(),
																fileDescriptor1
																		.getStartOffset(),
																fileDescriptor1
																		.getLength());
													} else if (b >= 1.0
															&& b < 2.0) {
														player.setDataSource(
																fileDescriptor2
																		.getFileDescriptor(),
																fileDescriptor2
																		.getStartOffset(),
																fileDescriptor2
																		.getLength());
													} else if (b >= 2.0
															&& b < 3.0) {
														player.setDataSource(
																fileDescriptor3
																		.getFileDescriptor(),
																fileDescriptor3
																		.getStartOffset(),
																fileDescriptor3
																		.getLength());
													} else if (b >= 3.0
															&& b < 4.0) {
														player.setDataSource(
																fileDescriptor4
																		.getFileDescriptor(),
																fileDescriptor4
																		.getStartOffset(),
																fileDescriptor4
																		.getLength());
													} else if (b >= 4.0
															&& b <= 5.0) {
														player.setDataSource(
																fileDescriptor5
																		.getFileDescriptor(),
																fileDescriptor5
																		.getStartOffset(),
																fileDescriptor5
																		.getLength());
													}

													player.prepare();

													player.start();

												} catch (Exception e) {
													Log.i("test", e.toString());
												}
											}
										}
									}

									// 扩展接口，暂时没有回调
									@Override
									public void onEvent(int arg0, int arg1,
											int arg2, Bundle arg3) {

									}

									// 出错回调
									@Override
									public void onError(SpeechError error) {

										// 如果出错关闭PopUpWindow
										if (null != popupWindow
												&& popupWindow.isShowing()) {
											popupWindow.dismiss();
										}

										flag = false;

										// 重置状态
										for (int i = 0; i < datas.size(); i++) {
											datas.get(i).isPlay = false;
										}

										// 隐藏加载框显示评分框
										info.isShowScore = true;
										info.isShowDialog = false;
										notifyDataSetChanged();

										UiHelper.toast(context, "未检测到录音。。。");
									}

									// 说话结束回调
									@Override
									public void onEndOfSpeech() {

									}

									// 开始说话回调
									@Override
									public void onBeginOfSpeech() {

									}
								});
					}

					break;

				case MotionEvent.ACTION_UP:

					// 停止录音
					if (null != mSpeechEvaluator) {
						mSpeechEvaluator.stopEvaluating();
					}

					// 松下的操作
					if (null != popupWindow && popupWindow.isShowing()) {
						popupWindow.dismiss();
					}

					// 同时开启评测功能,让右边的加载框进行展示
					if (flag == true) {
						info.isShowDialog = true;
						info.isShowScore = false;
					} else {
						info.isShowDialog = false;
						info.isShowScore = true;
					}

					notifyDataSetChanged();

					break;

				default:

					break;
				}

				return true;
			}
		});

		// 播放按钮的点击事件
		lvPlay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// 清除动画效果
				if (null != newAnimationDrawable) {
					newAnimationDrawable.stop();
					lvTopLaBa.setImageResource(R.drawable.lb);
				}
				
				
				// 获取录音文件的地址
				if (!TextUtils.isEmpty(info.audioPath)) {

					// 同步状态
					// 让其它条目的播放按钮变成停止状态
					for (int i = 0; i < datas.size(); i++) {
						if (info != datas.get(i)) {
							datas.get(i).isPlay = false;
						}
					}

					info.isPlay = true;

					notifyDataSetChanged();

					// 创建音频播放对象
					if (player != null) {
						player.release();
					}
					player = new MediaPlayer();

					// 设置完成播放的监听
					player.setOnCompletionListener(new OnCompletionListener() {

						@Override
						public void onCompletion(MediaPlayer mp) {
							if (player != null) {
								player.release();
								player = null;
							}

							// 改变图标
							info.isPlay = false;

							notifyDataSetChanged();
						}
					});

					// 播放录制的本地音频
					try {
						player.setDataSource(info.audioPath);
						player.prepareAsync();

						player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
							@Override
							public void onPrepared(MediaPlayer mp) {

								player.start();
							}
						});

					} catch (Exception e) {
						Log.i("test", e.toString());
					}
				} else {
					
					// 清除动画效果
					if (null != newAnimationDrawable) {
						newAnimationDrawable.stop();
						lvTopLaBa.setImageResource(R.drawable.lb);
					}
					
					// 创建音频播放对象
					if (player != null) {
						player.release();
					}
					player = new MediaPlayer();

					
					
					UiHelper.toast(context, "请先录音");

					return;
				}
			}
		});
	}

	/**
	 * 设置讯飞语音录制对象的参数方法
	 */
	private void setParams(Context context) {

		mSpeechEvaluator = SpeechEvaluator.createEvaluator(context, null);

		// 设置评测语种
		mSpeechEvaluator.setParameter(SpeechConstant.LANGUAGE, "en_us");
		// 设置评测题型
		// mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
		// "read_word");
		mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
				"read_sentence");
		// 设置试题编码类型
		mSpeechEvaluator.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
		// 设置前、后端点超时
		mSpeechEvaluator.setParameter(SpeechConstant.VAD_BOS, "5000");
		mSpeechEvaluator.setParameter(SpeechConstant.VAD_EOS, "1800");
		// 设置录音超时，设置成-1 则无超时限制
		mSpeechEvaluator.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");
		// 设置结果等级，不同等级对应不同的详细程度
		mSpeechEvaluator.setParameter(SpeechConstant.RESULT_LEVEL, "complete");
		// 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		// 注：AUDIO_FORMAT参数语记需要更新版本才能生效
		mSpeechEvaluator.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
	}

	/**
	 * 单独配置讯飞存放录音文件的方法
	 * 
	 * @param postion
	 */
	private void setAudioPath(int postion) {
		// 配置录音文件存放的位置
		mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
				Environment.getExternalStorageDirectory().getAbsolutePath()
						+ "/msc/" + "ice" + postion + ".wav");
	}

	/**
	 * 根据当前页面获取录音文件的路径的方法
	 * 
	 * @return
	 */
	private String getAmrPath(int postion) {
		File file = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/msc/" + "ice" + postion + ".wav");
		return file.getAbsolutePath();
	}

	
	
	public void stopPlayer() {
		// TODO Auto-generated method stub
		// 创建音频播放对象
		if (player != null) {
			player.release();
		}
	}

	/**
	 * 弹出录音的PopUpwindow
	 */
	private void showRecordPop() {
		view = View.inflate(context, R.layout.pop_record, null);
		lvPopRecord = (ImageView) view.findViewById(R.id.lv_pop_record);
		// 给顶部的图片设置帧动画
		lvPopRecord.setImageResource(R.drawable.record_anim);

		// 获取帧动画对象
		animationDrawable = (AnimationDrawable) lvPopRecord.getDrawable();

		// 开启帧动画
		animationDrawable.start();

		popupWindow = new PopupWindow(view,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT);

		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());

		popupWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				if (null != animationDrawable) {
					animationDrawable.stop();
				}
			}
		});
		popupWindow.showAtLocation(activity.getWindow().getDecorView(),
				Gravity.CENTER, 0, 0);
	}

}
